<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'

const props = defineProps<{
  text: string
  position?: 'top' | 'bottom' | 'left' | 'right'
  background?: string
}>()

const textRef = ref<HTMLElement>()
const showTooltip = ref(false)
const tooltipVisible = ref(false)

const position = props.position ?? 'bottom'
const background = props.background ?? '#333'

const checkOverflow = () => {
  if (textRef.value) {
    showTooltip.value = textRef.value.scrollWidth > textRef.value.clientWidth
  }
}

onMounted(() => {
  nextTick(checkOverflow)
})

watch(() => props.text, () => {
  nextTick(checkOverflow)
})

const onMouseEnter = () => {
  if (showTooltip.value) tooltipVisible.value = true
}
const onMouseLeave = (e: MouseEvent) => {
  const related = e.relatedTarget as HTMLElement
  if (!related?.closest('.tooltip-popup')) {
    tooltipVisible.value = false
  }
}
const onTooltipLeave = () => {
  tooltipVisible.value = false
}
</script>

<template>
  <div class="tooltip-wrapper" @mouseenter="onMouseEnter" @mouseleave="onMouseLeave">
    <div ref="textRef" class="tooltip-cell">{{ text }}</div>

    <div
        v-if="tooltipVisible"
        class="tooltip-popup"
        :style="{
        backgroundColor: background
      }"
        :class="'position-' + position"
        @mouseleave="onTooltipLeave"
    >
      {{ text }}
    </div>
  </div>
</template>

<style scoped>
.tooltip-wrapper {
  position: relative;
  display: inline-block;
}

.tooltip-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tooltip-popup {
  position: absolute;
  z-index: 1000;
  color: white;
  padding: 6px 10px;
  border-radius: 4px;
  max-width: 300px;
  word-break: break-word;
  white-space: normal;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  pointer-events: auto;
}

/* 定义位置 */
.position-bottom {
  top: 100%;
  left: 0;
  margin-top: 4px;
}

.position-top {
  bottom: 100%;
  left: 0;
  margin-bottom: 4px;
}

.position-left {
  right: 100%;
  top: 0;
  margin-right: 4px;
}

.position-right {
  left: 100%;
  top: 0;
  margin-left: 4px;
}
</style>